package com.honeycomb.db.dao;

import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.honeycomb.common.logger.HoneyCombLogger;
import com.honeycomb.common.logger.HoneyCombLoggerFactory;

/**
 * Hibernate Dao基类
 * @author WangHua
 * @param <T>
 * @param <PK>
 */
public abstract class BaseHibernateDao<T, PK extends Serializable> extends HibernateDaoSupport implements BaseDao<T, PK>{

	protected HoneyCombLogger logger = HoneyCombLoggerFactory.getLogger(this.getClass());
	
	private Class<T> entityPOJO;
	public BaseHibernateDao() {
		Type type = getClass().getGenericSuperclass();
		Type trueType = ((java.lang.reflect.ParameterizedType) type).getActualTypeArguments()[0];
        this.entityPOJO = (Class<T>) trueType;
    }

	@Override
	public PK add(T t) {  
		return (PK)this.getHibernateTemplate().save(t);
	}
	
	public void addAll(List<T> list) {  
		this.getHibernateTemplate().saveOrUpdateAll(list);
	}

	@Override
	public void update(T t) {
		this.getHibernateTemplate().update(t);;
	}

	@Override
	public void delete(PK id) {
		T me = findById(id);
		if(me != null) {
			this.getHibernateTemplate().delete(findById(id));
		}
	}

	@Override
	public T findById(PK id) {
		logger.info("-----------------------------findById-----------------------------");
		logger.info("-----currentClass: "+ entityPOJO);
		return this.getHibernateTemplate().get(entityPOJO, id);
	}

	@Override
	public List<T> findAll() {
		logger.info("-----------------------------findAll-----------------------------");
		return this.getHibernateTemplate().loadAll(entityPOJO);
	}

//	public int getNextPrimaryKeyForIntColumn(){
//		String fullClassName = this.entityPOJO.toString();
//		logger.info("fullClassName: ="+fullClassName);
//		String[] c = fullClassName.split("\\.");
//		logger.info("c.length---"+c.length);
//		String className = c[c.length - 1];
//		String HQLKey = "Get_Next_Num_" + className;
//		String HQLValue = ITOSSPropFactory.getInstance().getValue(HQLKey);
//		if(StringUtils.isEmpty(HQLValue)){
//			throw new DaoException("No Value specified for HQLKEY: "+HQLKey);
//		}
//		List list = this.getHibernateTemplate().find(HQLValue);
//		Integer it = (Integer)list.get(0);
//		int nextNum = 0;
//		if(it == null){
//			HQLKey = "Get_Next_Num_" + className + "_START_INDEX";
//			HQLValue = ITOSSPropFactory.getInstance().getValue(HQLKey);
//			if(StringUtils.isEmpty(HQLValue)){
//				throw new DaoException("No Value specified for HQLKEY: "+HQLKey);
//			}
//			nextNum = Integer.parseInt(HQLValue);
//		}else{
//			nextNum = it.intValue() + 1;
//		}
//		return nextNum;
//	}
	
}	
